package com.xyzwps.server.paimon.it

import com.xyzwps.server.paimon.app.dto.Me
import com.xyzwps.server.paimon.common.Utils
import org.springframework.graphql.test.tester.HttpGraphQlTester
import org.junit.jupiter.api.Assertions.*

open class GqlTestBase(port: Int) {

    protected val graphQlTester: HttpGraphQlTester

    init {
        val webClient = UiTestHelper.createWebTestClient("http://localhost:$port/graphql")
        graphQlTester = HttpGraphQlTester.create(webClient)
    }

    protected fun registerAndLogin(): Pair<Me, String> {
        val phone = UiTestHelper.genPhone()
        val registerDkey = graphQlTester.document("mutation { registerSendVcode(input: { phone: \"$phone\" }) } ")
            .execute()
            .path("registerSendVcode")
            .entity(String::class.java)
            .get()

        graphQlTester.document("mutation { register(input: { phone: \"$phone\", vcode: \"666666\", dkey: \"$registerDkey\" }) } ")
            .execute()
            .path("register")
            .valueIsNull()

        val loginDkey = graphQlTester.document("mutation { loginSendVcode(input: { phone: \"$phone\" }) } ")
            .execute()
            .path("loginSendVcode")
            .entity(String::class.java)
            .get()

        val me =
            graphQlTester.document("mutation { login(input: { phone: \"$phone\", vcode: \"666666\", dkey: \"$loginDkey\" }) { id nickname createdAt token } } ")
                .execute()
                .path("login")
                .entity(Me::class.java)
                .get()

        assertNotNull(me.id)
        assertEquals(Utils.maskPhone(phone), me.nickname)
        assertNotNull(me.createdAt)
        val token = me.token
        assertNotNull(token)

        return (me to token!!)
    }
}
